<template>
  <div class="layout">
    <Layout>
      <Layout :style="{ padding: '0 0px 0px' }">
        <Content :style="{ padding: '0px', minHeight: '635px', background: '#fff', }">
          <div class="receiver">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
              <FormItem label="收件人" prop="sender">
                <Input v-model="formValidate.receiver" placeholder="请输入收件人名字"></Input>
              </FormItem>
              <div v-if="open === true"><!--  判断-->
                <FormItem label="抄送" prop="anotherSender">
                  <Input v-model="formValidate.anotherSender"></Input>
                </FormItem>
              </div>
              <div v-if="open === false">
                <FormItem label="" prop="link">
                  <a @click="open = true">添加抄送</a>
                </FormItem>
              </div>
              <div v-else>
                <FormItem label="" prop="link">
                  <a @click="open = false">删除抄送</a>
                </FormItem>
              </div>
              <FormItem label="主题" prop="theme">
                <Input v-model="formValidate.theme"></Input>
              </FormItem>
              <FormItem prop="file">
              <el-upload class="upload-demo" action=""
                     :on-change="upload"
                     :auto-upload="false"
                     :show-file-list="false"
                     :before-upload="beforeUpload"
                     :file-list="fileList"
                     :limit="3"
                   >
            <el-button style="color: white; border-radius: 30px;height: 30px;background: linear-gradient(90deg,#3cadeb,#9c88ff);">上传附件</el-button>
          </el-upload>
            <p style="color: darkgray;font-size:5px;">可以在此上传你的附件，包括.doc、.docx、.zip、.txt、.jpg等文件、压缩包和图片，个数不超过3个，每个不超过100MB</p>
          
              </FormItem>
              <FormItem>
                <div v-if="showDiv">
                <div v-for="item in fileInList" :key="item.name">
                <PageHeader
                    :breadcrumb-list="breadcrumbList"
                    :tab-list="tabList"
                    :title="item.name"
                    :logo="item.url"
>
                  <template #action>
                      <ButtonGroup>
                          <!-- <Button type="primary" @click="previewImage(item.url)">预览</Button> -->
                      </ButtonGroup>
                      <Button type="error" @click="delefile(item.name)">删除</Button>
                                    </template>
                      <template #content>
                          <DescriptionList :col="2">
                              <Description term="文件名字：">{{ item.name }}</Description>
                              <Description term="字节大小：">{{ item.size }}</Description>
                              <Description term="最后修改时间：">{{ item.modify }}</Description>
                          </DescriptionList>
                      </template>
                      <template #extra>
                          <p style="color: #808695">状态</p>
                          <p style="font-size: 24px;color: aqua;">已上传</p>
                      </template>
                    </PageHeader> 
                  </div>
                </div>
        </FormItem>
              <FormItem label="正文" prop="text">
                <Input v-model="formValidate.text" type="textarea" :rows="10" />
              </FormItem>
              <FormItem>
                <div style="float: left;">
                  <p>发件人：</p>
                </div>
                <div style="float: left;">
                  <Poptip v-model="visible">
                    <a>{{ name }}</a><a>{{ SenderName }}</a>
                    <template #title> 
                      <div><i>{{ title1 }}</i></div>
                    </template>
                    <template #content>
                      <div style="float: left;">
                        <p>发送昵称：</p>
                      </div>
                      <div style="float: left;">
                        <p>{{ name }}</p>
                      </div>
                      <div style="float: left;padding-left: 6px;">
                        <a style="color: blue;" @click="modal = true">修改</a>
                      </div>
                    </template>
                  </Poptip>
                </div>
              </FormItem>
            </Form>

            <Modal title="修改昵称" v-model="modal" class-name="vertical-center-modal">
              <Input v-model="name" placeholder="请输入昵称" style="width: 300px" />
            </Modal>
            <div style="padding-left:80px">
              <space wrap>
                <Button @click="sendEmail">发送</Button>
              </space>
            </div>
          </div>
        </Content>
      </Layout>
    </Layout>
  </div>
</template>

<script>
/* import 'viewerjs/dist/viewer.css';
import Viewer from 'v-viewer'; */
export default {
  name: "Vuesend",
  /* components: {
    Viewer
  }, */
  data() {
    return {
      /* viewerOptions: {
        inline: false,
        button: true,
        navbar: true,
        title: true,
        toolbar: true,
        tooltip: true,
        movable: true,
        zoomable: true,
        rotatable: true,
        scalable: true,
        transition: true,
        fullscreen: true,
        keyboard: true,
        url: 'data-original'
      }, */
      fileList:[],
      fileInList:[],
      fileNameMap: {} , // 新增的对象，用于保存文件 UUID 和原始文件名的映射
      formValidate: {
        receiver:"",
        anotherReceiver:'',
        theme: '',
        text: ''
      },
      open: false,
      SenderName: "",
      name: "",
      modal: false,
      showDiv:true,//局部刷新页面,
      CurrentUser:"", // 当前用户
      DefaultUser: "default_user@example.com" ,// 默认用户
      savedFormData: {}  // 用于保存临时表单数据
    }
  },
  created(){
   this.showFileList();
   this.getCurrentUsers(); // 获取当前用户
  },
  methods: {
    refreshDiv(){
      this.showDiv=false;
      setTimeout(()=>{
        this.showDiv=true;
      },100);
    },
    sendEmail() {
      console.log("准备发送邮件:", this.formValidate); // 添加准备发送邮件的日志
      console.log("当前用户:", this.CurrentUser); // 添加检查当前用户的日志

      // 如果当前用户为空，则使用默认用户
      const sender = this.CurrentUser || this.DefaultUser;

      this.$store.dispatch('email/sendEmail', {
        "sender": sender,
        "subject": this.formValidate.theme,
        "password": "sotwiwatqooodcdb",
        "receiver": this.formValidate.receiver,
        "content": this.formValidate.text
      })
      .then(res => {
        console.log("发送邮件请求成功，后端返回的数据:", res); // 添加确认发送邮件请求成功的日志
        this.$router.push("/EmailSystemPages/SendEmail/Success");
        this.$message({
          type: "success",
          message: "发送成功"
        });
      })
      .catch(error => {
        console.error("发送邮件请求出错:", error); // 添加发送邮件请求出错的日志
        this.$message({
          type: "error",
          message: "失败"
        });
      });
    },
    handleExceed(files, fileList){
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    /* previewImage(url) {
      this.$nextTick(() => {
        const viewer = new Viewer(document.getElementById('preview-image'));
        viewer.show();
      });
    }, */
    getCurrentUsers(){
      this.$store.dispatch('user/getCurrentUser',{})
        .then(res => {
          console.log("current user")
          console.log(res)
          if(res.data.CurrentUser!=null){
            this.CurrentUser=res.data.CurrentUser;
            this.SenderName=res.data.CurrentUser;
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            type: "error",
            message: "还未登录"
          })
          this.$router.push("/login")
        })
     },


    upload(file){
      console.log('upload:', file);
      let formData = new FormData();
      formData.append("file", file.raw);
      
      // 保存表单数据到临时变量
      this.savedFormData = { ...this.formValidate };

      this.$store.dispatch('email/upload',formData)
          .then(res => {
            this.refreshDiv();
            /* this.showFileList();   */    
            // 保存文件 UUID 和原始文件名的映射
            this.fileNameMap[res.data.fileUUID] = file.raw.name;
            this.showFileList(); // 在保存映射后立即更新文件列表


           // 恢复表单数据        
           this.formValidate = { ...this.savedFormData };

            this.$message({
              type: "success",
              message: "上传成功"
            })
          })
          .catch(error =>{
            console.log("file.size",file.size)
            if(file.size>1048576){
            this.$message({
              type: "error",
              message: "附件大于100MB,上传失败"
            })
          }
          })
    },
    delefile(name){
      this.$store.dispatch('email/deleteFile',{"filename":name})
          .then(res => {
            this.refreshDiv();
            this.showFileList();
           var formValidatetemp={
                receiver:this.formValidate.receiver,
                anotherReceiver:this.formValidate.anotherReceiver,
                theme: this.formValidate.theme,
                text:this.formValidate.text
              };
          this.formValidate.receiver=formValidatetemp.receiver;
               this.formValidate.anotherReceiver=formValidatetemp.anotherReceiver;
          this.formValidate.theme=formValidatetemp.theme;
        this.formValidate.text=formValidatetemp.text;
           this.refreshDiv();
            this.$message({
              type: "success",
              message: "删除成功"
            })
          })
          .catch(error =>{
           
            this.$message({
              type: "error",
              message: "删除失败"
            })
          })
    },
    showFileList() {
  this.$store.dispatch('email/getFileList')
    .then(res => {
      console.log("res.data", res.data);
      var data = res.data;

      // 检查并打印返回的数据结构
      if (!data.fileList || !Array.isArray(data.fileList)) {
        console.error("Invalid file list data", data.fileList);
        this.$message({
          type: "error",
          message: "文件列表数据无效"
        });
        return;
      }
      if (!Array.isArray(data.fileSize) || !Array.isArray(data.lastModify)) {
        console.error("Invalid file size or last modify data", data.fileSize, data.lastModify);
        this.$message({
          type: "error",
          message: "文件大小或最后修改数据无效"
        });
        return;
      }

      // 清空文件列表
      this.fileInList = [];

      // 处理文件列表
      for (var i = 0; i < data.fileList.length; i++) {
        var fileMessage = { name: "", size: "", modify: "", url: "" };

        var fileUUID = data.fileList[i];
        // 使用保存的原始文件名，如果找不到则使用 UUID 名称
        fileMessage.name = this.fileNameMap[fileUUID] || fileUUID;
        fileMessage.size = data.fileSize[i] || '未知大小';
        fileMessage.modify = data.lastModify[i] || '未知修改时间';

        if (fileMessage.name.endsWith(".doc") || fileMessage.name.endsWith(".docx")) {
          fileMessage.url = "https://ts1.cn.mm.bing.net/th/id/R-C.22165c0f6cd4ab684933ee59a879ff0a?rik=Ku3CssKyl96gfw&riu=http%3a%2f%2ficonbug.com%2fdata%2f4d%2f507%2f9f5614cc92f4f1bb2de84cc6d9a6acd1.png&ehk=%2fMN9Q5ll0MhCViXggAj7JrGO5zopLHnpgsdloj%2bQgXI%3d&risl=&pid=ImgRaw&r=0";
        } else if (fileMessage.name.endsWith(".zip")) {
          fileMessage.url = "https://ts1.cn.mm.bing.net/th/id/R-C.f221e694fce50c185bee7c723a22cc74?rik=W9LVGwz3cgNhDg&riu=http%3a%2f%2fis3.mzstatic.com%2fimage%2fthumb%2fPurple20%2fv4%2f00%2f07%2ff4%2f0007f438-6f66-553c-3a37-0721ee34a4ba%2fsource%2f512x512bb.jpg&ehk=eUP9YCYnkOLMruztwhzYWeRM7ghUeCwRsJsHvCM73Cs%3d&risl=&pid=ImgRaw&r=0";
        } else {
          fileMessage.url = "https://img.ixintu.com/download/jpg/20200912/e7308659aa9682aa2f3b0b135755e926_512_512.jpg!ys";
        }

        console.log("fileMessage", fileMessage);
        this.fileInList.push(fileMessage);
      }

      console.log("Parsed File List:", this.fileInList);
      this.$message({
        type: "success",
        message: "文件列表获取成功"
      });
    })
    .catch(error => {
      console.error("Failed to get file list", error);
      this.$message({
        type: "error",
        message: "获取文件错误"
      });
    });
}


   }
  }
</script>

<style scoped>
.col-border {
  border-right: 1px solid var(--el-border-color);
  margin-right: 20px;
}

.top {
  text-align: center;
}

.receiver {
  padding-top: 20px;
}
</style>
